package com.kun.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.kun.ann.EncDec;
import com.kun.constant.CoreConstant;
import com.kun.dto.BaseEncryptReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * 对请求参数解密
 *
 * @author kun.li
 */
@Slf4j
@RestControllerAdvice
public class HandlerRequestBody extends RequestBodyAdviceAdapter {


    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(EncDec.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        InputStream inputStream = inputMessage.getBody();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        IoUtil.copy(inputStream, outputStream);
        String requestBody = IoUtil.toStr(outputStream, Charset.defaultCharset());
        BaseEncryptReq baseEncryptReq = JSONUtil.toBean(requestBody, BaseEncryptReq.class);
        // 将body解密
        byte[] decode = SecureUtil.aes(CoreConstant.AES_KEY.getBytes()).decrypt(baseEncryptReq.getEncryptBoyStr());
        try {
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    return IoUtil.toStream(decode);
                }

                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            log.error("接口入参解密错误:{}", e.getMessage());
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}
